<template>
  <a-form-item
    :key="element.metaRefresh"
    :name="element.field"
    :label="element.componentProps.label"
    :rules="element.componentProps.rules"
  >
    <div v-if="element.render">
      <component :is="element.render"></component>
    </div>
    <a-select
      v-else
      allowClear
      v-model:value="element.componentProps.value"
      class="m-2"
      placeholder="请选择一条数据"
      @change="selectChange"
    >
      <a-select-option
        v-for="item in element.componentProps.options"
        :key="item.value"
        :value="item.value"
        >{{ item.label }}</a-select-option
      >
    </a-select>
  </a-form-item>
</template>

<script lang="ts">
import {
  defineComponent,
  inject,
  toRefs,
  watch,
  reactive,
  computed,
  onMounted,
} from "vue";
import type { LowCodeImp } from "@/components/low-code/core/type";
import { useMergeConfig } from "@/components/low-code/pc-library/hooks/mergeConfig";

export default defineComponent({
  name: "selectWidget",
  props: ["element"],
  setup(props) {
    const getLowCodeInstance = inject("getLowCodeInstance") as Function;
    const lowCode = getLowCodeInstance() as LowCodeImp;
    const { element } = toRefs(props);

    useMergeConfig(element, lowCode.formController.getSchemas(), lowCode);
    const selectChange = (value: any) => {
      element.value.componentProps?.onChange
        ? element.value.componentProps.onChange(value)
        : element.value.componentProps.onChangeEvents.map(async (code: any) => {
            await lowCode.eventCenterController.fire(code);
          });
    };

    return {
      element,
      selectChange,
    };
  },
});
</script>

<style scoped>
.a-select {
  width: 100%;
}
</style>
